﻿$HASH = {
    change: {
        state: false,
        data: {}
    },
    history: [],
    historyNum: 0,
    iframeScrollTop: 0,
    siteSkinTempId: ''
};
var staticFunctions = {
    paragraph: 'articleEditor',
    text: 'textEditor',
    image: 'setImage'
};
var maxColumn = 6,
elToolsPanelHeight = 84,
editorMode = false,
pageData = {},
pageSettings = {},
dragElArr = ['section', 'row', 'app'],
pathName = {
    section: '区块',
    column: '列',
    row: '行',
    header: '页头',
    wrapper: '包裹',
    container: '容器',
    header: '页头',
    main: '页中',
    footer: '页尾'
},
screensName = {
    'basic': '基本',
    'min1200': '宽屏电脑',
    '961_1199': 'pad-横屏',
    '768_960': 'pad-竖屏',
    '480_767': '手机-横屏',
    'max479': '手机-竖屏'
},
styleToolsTop = '<li data-type="basic"><a href="javascript:;"><span class="icon-pencil active" title="' + screensName['basic'] + '" data-tips="3_t"></span></a></li><li data-type="min1200" rulers="max"><a href="javascript:;"><span class="icon-screen active" title="' + screensName['min1200'] + '" data-tips="3_t"></span></a></li><li data-type="961_1199" rulers="1024"><a href="javascript:;"><span class="icon-x-pad" title="' + screensName['961_1199'] + '" data-tips="3_t"></span></a></li><li  data-type="768_960" rulers="768"><a href="javascript:;"><span class="icon-tablet" title="' + screensName['768_960'] + '" data-tips="3_t"></span></a></li><li data-type="480_767" rulers="480"><a href="javascript:;"><span class="icon-x-mobile" title="' + screensName['480_767'] + '" data-tips="3_t"></span></a></li><li data-type="max479" rulers="320"><a href="javascript:;"><span class="icon-mobile" title="' + screensName['max479'] + '" data-tips="3_t"></span></a></li>',
styleToolsFoot = '',
copyToolsFoot = '<a href="javascript:;" class="setPanelFootBtn" role="copySetting"><i class="icon-paste"></i> 复制本页设置到其它网页</a>',
bodyData = {
    items: [{
        "name": "插入",
        "toolsTop": "",
        "toolsFoot": copyToolsFoot,
        "html": "<div role='siteModule'></div>",
        "init": setSiteModule
    },
    {
        "name": "属性",
        "toolsTop": "",
        "toolsFoot": copyToolsFoot,
        "html": "<div role='pageSettings'></div>",
        "init": setPageInfo
    },
    {
        "name": "样式",
        "toolsTop": '<ul class="clearfix" data-selector="">' + styleToolsTop + '</ul>',
        "toolsFoot": copyToolsFoot,
        "html": "<div role='styleContainer'  data-selector=''></div>",
        "init": function () {
            setElStyle('body', '')
        }
    },
    {
        "name": "皮肤",
        "toolsTop": "",
        "toolsFoot": copyToolsFoot,
        "html": "<div role='pageSkins'></div>",
        "init": setPageSkins
    },
    {
        "name": "模板",
        "toolsTop": "",
        "toolsFoot": "<a href='javascript:;' class='setPanelFootBtn' role='savePageTemplate'><i class='icon-disk'></i> 保存本页为模板</a>",
        "html": "<div role='pageTemplates'></div>",
        "init": setPageTemplates
    }]
},
appInit = $.noop;
var pageFrame = $('#pageFrame'),
frameContainer = $('#frameContainer');
if (supportTouch) {
    pageFrame.css('height', 'auto');
    frameContainer.on({
        scroll: function () {
            $HASH['iframeScrollTop'] = this.scrollTop
        }
    }).niceScroll()
};
var saveBtn = $('#saveBtn'),
undoBtn = $('#undoBtn'),
redoBtn = $('#redoBtn');
saveBtn.on(click,
function () {
    if ($(this).hasClass('active')) {
        save()
    }
});
undoBtn.on(click,
function () {
    if ($(this).hasClass('active')) {
        undo()
    }
});
redoBtn.on(click,
function () {
    if ($(this).hasClass('active')) {
        redo()
    }
});
var frameWidth = 'Max',
rulers = $('#rulers'),
pageContainer = $('#pageContainer');
$('span', rulers).litabs({
    callBack: function (el) {
        var frameWidth = el.data('width') == 'max' ? '100%' : el.data('width');
        frameContainer.width(frameWidth);
        resetToolsPosition('', 1)
    }
});
function resizeIframe() {
    var maxWidth = pageContainer.width(),
    flag = false,
    curWidth;
    $('span', rulers).each(function () {
        var width = $(this).data('width');
        if (width != 'Max') {
            if (maxWidth >= width) {
                curWidth = width;
                return false
            }
        }
    });
    if (maxWidth <= 1024) {
        if (frameWidth == 'Max') {
            flag = true
        } else if (frameWidth > curWidth) {
            flag = true
        }
    };
    if (flag) {
        setRulers(curWidth)
    }
};
function setRulers(rw, width) {
    var widthData = {
        'basic': 'max',
        'min1200': 'max',
        '961_1199': '1024',
        '768_960': '768',
        '480_767': '480',
        'max479': '320'
    };
    $('span[data-width="' + (rw ? rw : widthData[width]) + '"]', rulers).trigger(click)
};
var toolsMain = $('#toolsMain'),
currentToolsId = '';
toolsMain.delegate('a[role=toggleBtn]', click,
function (e) {
    $('#pagePanel').toggleClass('openPanel');
    $(this).toggleClass('on off').hideTips();
    if ($(this).hasClass('on')) {
        $(this).attr('title', '展开');
        $('div.boxscroll', toolsMain).getNiceScroll().hide()
    } else {
        $(this).attr('title', '收起');
        $('div.active div.boxscroll', toolsMain).getNiceScroll().resize();
        $('div.active div.boxscroll', toolsMain).getNiceScroll().show()
    }
    e.preventDefault();
    e.stopPropagation()
}).delegate('div.setPanelFoot a[role]', click,
function (e) {
    switch ($(this).attr('role')) {
        case 'savePageTemplate':
            top.savePageTemplate(pageId);
            break
    };
    e.preventDefault();
    e.stopPropagation()
}).delegate('div.moreSetStyle li', {
    mouseenter: function () {
        $('#mostyleHightlight', pageBody).html('#' + currentToolsId + ' ' + $(this).data('selector') + '{border:1px solid #FF0}')
    },
    mouseleave: function () {
        $('#mostyleHightlight', pageBody).empty()
    }
});
$('#pagePanel .f_panel').on(click,
function () {
    if ($('a[role=toggleBtn]', toolsMain).hasClass('on')) {
        $('a[role=toggleBtn]', toolsMain).trigger(click)
    }
});
function setTools(id) {
    if (currentToolsId == id) return;
    currentToolsId = id;
    var data,
    toolsBar = $('ul[role=toolsBar]', toolsMain),
    toolsContainer = $('div[role="toolsContainer"]', toolsMain),
    toolsBarHtml = '';
    if (id == 'body') {
        data = bodyData.items
    } else {
        data = getElToolsData()
    };
    toolsContainer.find('div.boxscroll').getNiceScroll().remove();
    toolsContainer.empty();
    $('div.colorpicker').remove();
    $('div.sliderContainer').remove();
    $.each(data,
    function (i, item) {
        toolsBarHtml += '<li>' + item.name + '</li>';
        var mHtml = '';
        if (item.toolsTop) {
            mHtml += '<div class="tabs setMediaTab" role="toolsTop">' + item.toolsTop + '</div>'
        };
        mHtml += '<div class="f_panelMain boxscroll"><div class="boxPad" role="toolsWrapper">' + item.html + '</div></div>';
        if (item.toolsFoot) {
            mHtml += '<div class="setPanelFoot tc" role="toolsFoot">' + item.toolsFoot + '</div>'
        };
        toolsContainer.append('<div style="display:none">' + mHtml + '</div>').find('div.boxscroll').niceScroll({
            autohidemode: true,
            bouncescroll: true,
            zindex: 101,
            cursorwidth: 5,
            railpadding: {
                top: 0,
                right: 0,
                left: 0,
                bottom: 0
            }
        });
        toolsContainer.find('div.boxscroll').getNiceScroll().hide()
    });
    toolsBar.html(toolsBarHtml).find('li').litabs({
        callBack: function (el) {
            clearTips(toolsContainer);
            var num = el.data('i'),
            curData = data[num];
            if (curData['toolsTop']) {
                toolsMain.removeClass('hideTop')
            } else {
                toolsMain.addClass('hideTop')
            };
            if (curData['toolsFoot']) {
                toolsMain.removeClass('hideFoot')
            } else {
                toolsMain.addClass('hideFoot')
            };
            $('>div:eq(' + num + ')', toolsContainer).show().addClass('active').siblings().removeClass('active').hide().find('div.boxscroll').getNiceScroll().hide();
            resizeToolsScroll();
            if (!el.data('init')) {
                curData['init'](el);
                el.data('init', 1)
            }
        }
    })
};
function resizeToolsScroll() {
    $('div.active div.boxscroll', toolsMain).getNiceScroll().resize();
    $('div.active div.boxscroll', toolsMain).getNiceScroll().show()
};
var hash = $.cookie('hash');
$.cookie('hash', null);
try {
    $.extend($HASH, $.parseJSON(hash));
    if (!$HASH.siteId) {
        $('body').html('')
    }
} catch (bug) {
    $('body').html('')
};
eval($HASH['isr']);
delete $HASH['isr'];
eval($HASH['get']);
delete $HASH['get'];
function setModuleBox(data, type) {
    return '<li data-id="' + data.id + '" data-sole="' + data.sole + '" data-type="' + type + '"><div class="custom_module_box"><div class="custom_module_ico"><img width="64" height="64" src="' + data.icon + '"></div><p class="custom_module_name">' + data.name + '</p></div></li>'
};
function setSiteModule() {
    var container = $('div[role="siteModule"]', toolsMain),
    fn = function () {
        var html = '<div class="h6 ct_1">点击并拖动图标到左侧网页中</div>';
        $.each(top.$HASH['siteModule'],
        function (i, item) {
            html += '<dl class="setPanel" data-type="' + item.type + '"><dt><i class="trigon left ct_3 small"></i>' + item.name + '</dt><dd>';
            html += '<div class="setPanelMain ';
            if (item.type != 'app') {
                html += 'addPanelList"><ul class="clearfix">';
                if (item.items.length) {
                    $.each(item.items,
                    function (j, it) {
                        html += setModuleBox(it, item.type)
                    })
                };
                html += '</ul>'
            } else {
                html += '"><div>';
                if (item.items.length) {
                    $.each(item.items,
                    function (j, it) {
                        html += '<div class="h6 pt20 appToggle" data-id="' + it.id + '" data-staus="' + it.staus + '"><i class="lineTrigon left"><b class="ct_f"></b></i>' + it.name + '</div>';
                        if (it.items.length) {
                            html += '<div class="addPanelList setPanelMain"><ul class="clearfix">';
                            $.each(it.items,
                            function (i, il) {
                                html += setModuleBox(il, item.type)
                            });
                            html += '</ul></div>'
                        }
                    })
                };
                html += '</div>'
            };
            html += '</div></dd></dl>'
        });
        var moduleEl = $('<div>' + html + '</div>');
        container.empty().append(moduleEl);
        resizeToolsScroll();
        moduleEl.delegate('dt', click,
        function (e) {
            $(this).find('>i').toggleClass('top left');
            $(this).next().find('>div').toggleClass('active');
            resizeToolsScroll()
        }).delegate('div.appToggle', click,
        function (e) {
            $(this).find('>i').toggleClass('top left');
            $(this).next().toggleClass('active');
            resizeToolsScroll()
        });
        setDragModule(moduleEl);
        if (!$HASH['history'].length) {
            setTimeout(setHistory, 100)
        }
    };
    if (!top.$HASH['siteModule']) {
        container.html(getContentLoading());
        top.getSiteModule(fn,
        function (msg) {
            container.html(msg)
        })
    } else {
        fn()
    }
};
function setDragModule(el) {
    var offset = 10,
    il,
    it,
    canDrop = false,
    placeholder;
    $('div.custom_module_box', el).draggable({
        helper: 'clone',
        opacity: 0.8,
        zIndex: 1002,
        appendTo: 'body',
        containment: 'window',
        cursor: 'move',
        start: function () {
            il = pageFrame.offset().left;
            it = pageFrame.offset().top;
            placeholder = $('<div class="sortablePlaceholder"><div><b></b><i></i></div></div>').appendTo(pageBody).hide();
            $('#frameMask').show()
        },
        drag: function (event, ui) {
            canDrop = false;
            $('div[role="dragEl"]:not([dragDisabled]),div[role="dragEmptyEl"]:not([dragDisabled])', pageBody).each(function () {
                var kl = event.pageX - il,
                kt = event.pageY - it + $HASH['iframeScrollTop'],
                direction = '',
                $this = $(this);
                if (kl > $this.offset().left && kl < $this.offset().left + $this.outerWidth()) {
                    if (kt > $this.offset().top && kt < $this.offset().top + $this.outerHeight() / 2) {
                        direction = 'up'
                    } else if (kt < $this.offset().top + $this.outerHeight() && kt > $this.offset().top + $this.outerHeight() / 2) {
                        direction = 'down'
                    };
                    drop = true
                };
                if (direction == 'up') {
                    placeholder.insertBefore($this)
                } else if (direction == 'down') {
                    placeholder.insertAfter($this)
                };
                if (direction) {
                    placeholder.show();
                    canDrop = true
                }
            });
            if (canDrop) {
                placeholder.show()
            } else {
                placeholder.hide()
            }
        },
        stop: function () {
            var wrapper = placeholder.parent(),
            appEl = $(this).data('data', {
                sole: $(this).parent().data('sole'),
                id: $(this).parent().data('id'),
                type: $(this).parent().data('type')
            });
            placeholder.siblings('div[role="dragEmptyEl"]').remove();
            if (canDrop) {
                if (checkAppWrapper(wrapper, appEl)) {
                    if (checkSole(appEl)) {
                        loadDropApp(appEl, placeholder)
                    }
                }
            };
            placeholder.remove();
            $('#frameMask').hide()
        }
    })
};
function getUserGroupOptions() {
    var html = '';
    $.each(top.$HASH['userGroup'],
    function (i, item) {
        html += '<option value="' + item.id + '">' + item.name + '</option>'
    });
    return html
};
function setPageInfo() {
    var pageSettings = pageData.settings,
    container = $('div[role="pageSettings"]', toolsMain),
    getViewUrl = function (value) {
        return top.$HASH['site']['host'] + (value ? '/' + value : top.viewURL + pageId)
    },
    setViewUrl = function () {
        var value = $('input[name="url"]', container).val(),
        newUrl = getViewUrl(value);
        $('a[role="viewUrl"]', container).text(newUrl).attr('href', 'http://' + newUrl)
    },
    checkInfo = function ($this) {
        var name = $this.attr('name'),
        value = $this.val(),
        msg = '',
        state = 'pageData',
        changeInfo = function () {
            pageSettings[name] = enToString(value);
            pageData.settings = pageSettings;
            change(state)
        };
        switch ($this.attr('name')) {
            case 'url':
                if (value) {
                    if (!isLetterNumber(value)) {
                        $this.val('');
                        msg = '只能使用字母或数字'
                    } else if (value.length < 4) {
                        msg = '不能小于4个字符'
                    } else if (value.length > 32) {
                        msg = '不能大于32个字符'
                    }
                }
                break;
            case 'title':
                if (!value) {
                    msg = '标题不能为空！'
                }
                break;
            case 'authority':
                if (value == 'password') {
                    $('div[role="password"]', container).show();
                    var pwd = pageSettings.password ? pageSettings.password : getRandom();
                    $('input[name="password"]', container).val(pwd);
                    pageSettings['password'] = pwd
                } else {
                    $('div[role="password"]', container).hide();
                    $('input[name="password"]', container).hideTips()
                }
                break;
            case 'password':
                if (value.length < 4) {
                    msg = '不能小于4个字符'
                } else if (value.length > 32) {
                    msg = '不能大于32个字符'
                } else if (!isLetterNumber(value)) {
                    $this.val('');
                    msg = '只能使用字母或数字'
                }
                break;
            case 'tools':
                value = $this.attr('checked') ? 1 : 0;
                break;
            case 'header':
                value = $this.attr('checked') ? 1 : 0;
                if (value) {
                    $('#header', pageLayout).show()
                } else {
                    $('#header', pageLayout).hide()
                };
                state = 'all';
                break;
            case 'footer':
                value = $this.attr('checked') ? 1 : 0;
                if (value) {
                    $('#footer', pageLayout).show()
                } else {
                    $('#footer', pageLayout).hide()
                };
                state = 'all';
                break
        };
        if (msg) {
            $this.errorInput(msg)
        } else if (pageSettings[name] != enToString(value)) {
            if (name == 'url') {
                rpcJSON('checkPageUrl', {
                    pageId: pageId,
                    url: value
                },
                changeInfo,
                function () {
                    $this.errorInput('网址已存在，请换一个再试')
                })
            } else {
                changeInfo()
            }
        }
    },
    url = getViewUrl(pageSettings.url),
    html = '<div class="h6 ct_1">设置网页的基本属性</div>' + '<div role="settingsContainer">' + '<dl class="setPanel">' + '<dt><i class="trigon ct_3 small left"></i>自定义网址</dt>' + '<dd>' + '<div class="setPanelMain ct_2">' + '<div class="pt10">' + '网址<span class="ct_1">(4-32个字母、数字)</span>：' + '<div class="f_panelFrom">' + '<input name="url" type="text" class="inputText inputBlcok small" value="' + pageSettings.url + '" autocomplete="off" />' + '<a href="http://' + url + '" class="ct_2 h6 pt5" role="viewUrl" style="word-break:break-all;display:inline-block;width:100%" target="_blank">' + url + '</a>' + ' </div>' + '</div>' + '</dd></dl>' + '<dl class="setPanel">' + '<dt><i class="trigon ct_3 small left"></i>SEO优化</dt>' + '<dd>' + '<div class="setPanelMain  ct_2">' + ' <div class="pt10">' + '标题：' + '<div class="f_panelFrom">' + '<input name="title" type="text" class="inputText inputBlcok small " value="' + pageSettings.title + '" autocomplete="off"/>' + ' </div>' + ' </div>' + ' <div class="pt10">' + '描述：' + ' <div class="f_panelFrom">' + ' <textarea name="description" class="textarea inputBlcok ">' + pageSettings.description + '</textarea>' + '</div>' + '</div>' + ' <div class="pt10">' + '关键词(多个用逗号分隔)：' + ' <div class="f_panelFrom">' + ' <textarea name="keywords" class="textarea inputBlcok ">' + pageSettings.keywords + '</textarea>' + '</div>' + '</div>' + '</div></dd></dl>' + '<dl class="setPanel">' + '<dt><i class="trigon ct_3 small left"></i>高级设置</dt>' + '<dd>' + '<div class="setPanelMain  ct_2">' + '  <div class="pt10">' + '访问权限：' + '  <div class="f_panelFrom">' + '<select name="authority" class="select1" style="width:205px;">' + ' <option value="0">所有人</option>' + ' <option value="password">凭密码</option>' + getUserGroupOptions() + '</select>' + '</div>' + ' </div>' + ' <div class="pt10" ' + (pageSettings.authority != 'password' ? 'style="display:none;"' : '') + ' role="password">' + '访问密码<span class="ct_1">(4-32个字母、数字)</span>：' + ' <div class="f_panelFrom">' + '<input name="password" type="text" class="inputText inputBlcok  small" value="' + pageSettings.password + '" autocomplete="off"/>' + '</div>' + '</div>' + '<div class="pt10">' + '<label class="checkbox">' + '   <input type="checkbox" name="tools" value="1" ' + (pageSettings.tools == '1' ? 'checked' : '') + ' >显示右侧工具条' + ' </label>' + '</div>' + '  <div class="pt10">' + ' <label class="checkbox">' + ' <input type="checkbox" name="header" value="1" ' + (pageSettings.header == '1' ? 'checked' : '') + '>显示头部' + ' </label>' + '</div>' + '<div class="pt10">' + '<label class="checkbox">' + ' <input type="checkbox" name="footer" value="1" ' + (pageSettings.footer == '1' ? 'checked' : '') + '>显示底部' + ' </label>' + '</div>' + '</div></dd></dl>' + '</div>';
    container.html(html).find('div[role="settingsContainer"]').delegate('input[type="text"],textarea', {
        blur: function () {
            checkInfo($(this))
        }
    }).delegate('input[type="checkbox"]', click,
    function () {
        checkInfo($(this))
    }).delegate('select', 'change',
    function () {
        checkInfo($(this))
    }).delegate('input[name="url"]', {
        keyup: setViewUrl,
        paste: setViewUrl,
        blur: setViewUrl
    }).delegate('dt', click,
    function (e) {
        $(this).find('>i').toggleClass('top left');
        $(this).next().find('>div').toggleClass('active');
        resizeToolsScroll()
    }).find('input[type="text"],textarea').fancyInput();
    $('select[name="authority"] option[value="' + pageSettings.authority + '"]', container).attr('selected', 'selected');
    $('select[name="authority"]').fancySelect({
        fancyClass: 'fancySelect3'
    });
    resizeToolsScroll()
};
function setPageSkins() {
    var container = $('div[role="pageSkins"]', toolsMain),
    html = '<div class="h6 ct_1">更换本页的皮肤，不改变结构和内容</div>' + '<div class="pt10"><select class="select1" style="width:100%" role="colorCategories"></select></div><div class="custom_container_box "><div class="custom_template"><ul></ul>' + getContentLoading() + '</div></div>';
    container.html(html).find('select[role="colorCategories"]').setSelect($.merge([{
        id: 0,
        name: '全部颜色'
    },
    {
        id: 'history',
        name: '历史记录'
    }], top.$HASH['colors'])).fancySelect({
        fancyClass: 'fancySelect3'
    }).change(function () {
        lastId = '';
        getTemplates()
    });
    var contentLoading = container.find('div.loading:first'),
    scrollContainer = container.parents('div.boxscroll:first'),
    skinsContainer = container.find('div.custom_template > ul'),
    loadingEl = scrollContainer.find('div.loading:first'),
    scrollLoadTools = function (data, count, onLoad) {
        scrollContainer.off('scroll');
        scrollLoad({
            target: scrollContainer,
            contentContainer: skinsContainer,
            contentLoading: loadingEl,
            loadUrl: ajaxURL,
            data: data,
            count: count,
            onLoad: onLoad
        })
    },
    getTemplates = function () {
        var categories = container.find('select[role="colorCategories"]').val(),
        ids = categories == 'history' && top.$HASH.historyPageSkins.length ? top.$HASH.historyPageSkins : '';
        skinsContainer.empty();
        resizeToolsScroll();
        scrollLoadTools({
            color: categories,
            action: 'getPageSkins',
            ids: ids
        },
        15,
        function (backData) {
            $(backData).appendTo(skinsContainer);
            skinsContainer.find('li[data-id="' + pageData.skinId + '"]').addClass('active');
            resizeToolsScroll();
            loadingEl.hide()
        });
        loadingEl.fadeIn();
        $.post(ajaxURL, {
            count: 15,
            action: 'getPageSkins',
            color: categories,
            ids: ids
        },
        function (backData) {
            skinsContainer.html(backData);
            skinsContainer.find('li[data-id="' + $HASH['siteSkinTempId'] + '"]').addClass('active');
            resizeToolsScroll();
            loadingEl.hide()
        })
    };
    getTemplates();
    skinsContainer.delegate('li', click,
    function () {
        $(this).toActive(function (el) {
            changePageSkin($(el).data('id'), $(el).data('skin'))
        })
    })
};
function setPageTemplates() {
    var container = $('div[role="pageTemplates"]', toolsMain),
    html = '<div class="h6 ct_1">更换模板会替换本页内容和所有设置</div>' + '<div class="pt10" style="display:none;" role="selectConatiner"><span><select class="select1" style="width:100px" role="colorCategories"></select></span><span style="display:inline-block;margin-left:8px;"><select class="select1" style="width:100px" role="pageCategories"></select></span></div><div class="custom_container_box "><div class="custom_template"><ul></ul>' + getContentLoading() + '</div></div>';
    container.html(html);
    var colorCategoriesSelect = container.find('select[role="colorCategories"]'),
    pageCategoriesSelect = container.find('select[role="pageCategories"]'),
    categoriesMyDefault = [{
        id: 0,
        name: '全部分类'
    },
    {
        id: 'my',
        name: '我保存的'
    },
    {
        id: 'history',
        name: '预览历史'
    }],
    setDefault = function () {
        colorCategoriesSelect.setSelect($.merge([{
            id: 0,
            name: '全部颜色'
        }], top.$HASH['colors']));
        pageCategoriesSelect.setSelect($.merge(categoriesMyDefault, top.$HASH['pageTemplateCategories']));
        $('select', container).fancySelect({
            fancyClass: 'fancySelect3'
        }).change(function () {
            lastId = '';
            getTemplates()
        });
        $('div[role="selectConatiner"]', container).show();
        getTemplates()
    },
    contentLoading = container.find('div.loading:first'),
    scrollContainer = container.parents('div.boxscroll:first'),
    templateContainer = container.find('div.custom_template > ul'),
    loadingEl = scrollContainer.find('div.loading:first'),
    scrollLoadTools = function (data, count, onLoad) {
        scrollContainer.off('scroll');
        scrollLoad({
            target: scrollContainer,
            contentContainer: templateContainer,
            contentLoading: loadingEl,
            loadUrl: ajaxURL,
            data: data,
            count: count,
            onLoad: onLoad
        })
    },
    getTemplates = function () {
        var color = colorCategoriesSelect.val(),
        categories = pageCategoriesSelect.val(),
        ids = categories == 'history' && top.$HASH.historyPageTamplates.length ? top.$HASH.historyPageTamplates : '';
        templateContainer.empty();
        resizeToolsScroll();
        if (categories == 'history' && !ids) {
            templateContainer.html('<div class="empty">暂无历史记录</div>');
            return
        };
        scrollLoadTools({
            action: 'getPageTemplates',
            color: color,
            categories: categories,
            ids: ids
        },
        15,
        function (backData) {
            $(backData).appendTo(templateContainer);
            templateContainer.find('li[data-id="' + pageData.tamplateId + '"]').addClass('active');
            resizeToolsScroll();
            loadingEl.hide()
        });
        loadingEl.fadeIn();
        $.post(ajaxURL, {
            count: 15,
            action: 'getPageTemplates',
            color: color,
            categories: categories,
            ids: ids
        },
        function (backData) {
            templateContainer.html(backData);
            templateContainer.find('li[data-id="' + pageData.tamplateId + '"]').addClass('active');
            resizeToolsScroll();
            loadingEl.hide()
        })
    };
    templateContainer.delegate('a[role]', click,
    function () {
        var $this = $(this),
        li = $this.parents('li:first'),
        templateId = li.data('id');
        switch ($(this).attr('role')) {
            case 'delete':
                top.Confirm('模板删除后不能恢复，确定要删除这个模板吗？',
                function () {
                    li.hideRemove();
                    rpcJSON('deletePageTemplate', {
                        templateId: templateId
                    })
                });
                break;
            case 'select':
                changePageTemplate(templateId, $this);
                break;
            case 'preview':
                top.updateHistory('historyPageTamplates', templateId);
                top.createFrame('/c/admin/a/template/pageId/' + pageId + '/pageTemplateId/' + templateId, $('p', li).text() + '预览');
                break
        }
    });
    if (top.$HASH['pageTemplateCategories']) {
        setDefault()
    } else {
        rpcJSON('getPageTemplateCategories', '',
        function (backData) {
            top.$HASH['pageTemplateCategories'] = backData;
            setDefault()
        })
    }
};
var showTools = {};
$('#visibleBox').on(click,
function (e) {
    $(this).toggleClass('active');
    e.stopPropagation()
}).on('mouseleave',
function () {
    $(this).removeClass('active')
}).delegate('li', click,
function (e) {
    e.stopPropagation();
    $(this).toggleClass('active');
    if ($(this).hasClass('active')) {
        pageBody.addClass($(this).attr('role'))
    } else {
        pageBody.removeClass($(this).attr('role'))
    }
}).find('li').each(function () {
    showTools[$(this).attr('role')] = $(this).hasClass('active')
});
$(document).on(click,
function () {
    $('#visibleBox').removeClass('active')
});
function copySetting() {
    var fn = function () {
        var tree,
        el = $('<div class="p20"><div class="clearfix styleSet">' + '<div class="styleSetLeft">' + '<div class="ct_3"><b>选择设置</b></div>' + '<div class="pt10" >' + '<p><label class="checkbox"><input type="checkbox" value="tools">显示右侧工具条</label></p>' + '<p><label class="checkbox"><input type="checkbox" value="authority" >访问权限</label></p>' + '<p><label class="checkbox"><input type="checkbox" value="header">头部</label></p>' + '<p><label class="checkbox"><input type="checkbox" value="footer">底部</label></p>' + '<p><label class="checkbox"><input type="checkbox" value="skin" >皮肤</label></p>' + '</div>' + '</div>' + '<div class="styleSetLeft">' + '<div class="ct_3"><b>选择样式</b></div>' + '<div class="pt10" >' + '<p><label class="checkbox"><input type="checkbox" value="body_style" role="style" >网页样式</label></p>' + '<p><label class="checkbox"><input type="checkbox" value="wrapper_style" role="style" >网页包裹样式</label></p>' + '<p><label class="checkbox"><input type="checkbox" value="container_style" role="style" >网页容器样式</label></p>' + '<p><label class="checkbox"><input type="checkbox" value="header_style" role="style" >头部样式</label></p>' + '<p><label class="checkbox"><input type="checkbox" value="headerWrapper_style" role="style" >头部包裹样式</label></p>' + '<p><label class="checkbox"><input type="checkbox" value="headerContainer_style" role="style" >头部容器样式</label></p>' + '<p><label class="checkbox"><input type="checkbox" value="main_style" role="style" >页中样式</label></p>' + '<p><label class="checkbox"><input type="checkbox" value="mainWrapper_style" role="style" >页中包裹样式</label></p>' + '<p><label class="checkbox"><input type="checkbox" value="mainContainer_style" role="style" >页中容器样式</label></p>' + '<p><label class="checkbox"><input type="checkbox" value="footer_style" role="style" >底部样式</label></p>' + '<p><label class="checkbox"><input type="checkbox" value="footerWrapper_style" role="style" >底部包裹样式</label></p>' + '<p><label class="checkbox"><input type="checkbox" value="footerContainer_style" role="style" >底部容器样式</label></p>' + '</div>' + '</div>' + '<div class="styleSetRight">' + '<div class="ct_3"><b>选择要应用的网页</b></div>' + '<div style="height:400px;width:300px;" class="boxscroll" id="copyContainerScroll"><div class="pt10" id="copyTreeContainer">' + getContentLoading() + '</div></div>' + '</div>' + '</div></div>'),
        dialog = top.ConfirmDialog('复制本页设置到其它网页', el, {
            scroll: false,
            onBeforeClose: function (fn, type) {
                if (type == 'confirm') {
                    if ($('div.styleSetLeft input[value="header"]:checked', el).length) {
                        $('div.styleSetLeft:eq(1) input[value*="header"]', el).attr('checked', false)
                    };
                    if ($('div.styleSetLeft input[value="footer"]:checked', el).length) {
                        $('div.styleSetLeft:eq(1) input[value*="footer"]', el).attr('checked', false)
                    };
                    var setValue = getAllCheck($('div.styleSetLeft', el)).value,
                    selNodes = tree.getSelectedNodes();
                    if (!setValue.length) {
                        top.Alert('还没有选择设置选项')
                    } else if (!selNodes.length) {
                        top.Alert('还没有选择要应用的网页')
                    } else if (selNodes.length > top.copyMax) {
                        top.Alert('一次最多能同步' + top.copyMax + '个网页')
                    } else {
                        top.Confirm('<h3 class="ct_5">该操作会覆盖所选网页的相应设置，且不能撤销。<br>确定要继续操作吗？</h3>',
                        function () {
                            var pageStyles = '',
                            header = '',
                            footer = '',
                            headerStatic = '',
                            footerStatic = '',
                            selKey = $.map(selNodes,
                            function (node) {
                                return node.data.key
                            });
                            $('div.styleSetLeft input[role="style"]:checked', el).each(function () {
                                var value = $(this).val(),
                                id = value.replace('_style', '');
                                if ($('#' + value, pageBody).length) {
                                    if (!pageStyles) {
                                        pageStyles = {}
                                    };
                                    pageStyles[value] = $('#' + value, pageBody).parent().html()
                                }
                            });
                            if ($('div.styleSetLeft input[value="header"]', el).attr('checked') || $('div.styleSetLeft input[value="footer"]', el).attr('checked')) {
                                var html = '<div>' + getPageLayout() + '</div>';
                                if ($('div.styleSetLeft input[value="header"]', el).attr('checked')) {
                                    var $temp = $('<div></div>').append($(html).find('#container:first >#header,#container:first >hide_header >#header').clone(true));
                                    if (pageData.settings.header != '1') {
                                        header = '<hide_header>' + $temp.html() + '</hide_header>'
                                    } else {
                                        header = $temp.html()
                                    };
                                    headerStatic = '<div id="header_static">' + $('#header_static', pageBody).html() + '</div>';
                                    $temp.remove()
                                };
                                if ($('div.styleSetLeft input[value="footer"]', el).attr('checked')) {
                                    var $temp = $('<div></div>').append($(html).find('#container:first >#footer,#container:first >hide_footer >#footer').clone(true));
                                    if (pageData.settings.footer != '1') {
                                        footer = '<hide_footer>' + $temp.html() + '</hide_footer>'
                                    } else {
                                        footer = $temp.html()
                                    };
                                    footerStatic = '<div id="footer_static">' + $('#footer_static', pageBody).html() + '</div>';
                                    $temp.remove()
                                }
                            };
                            rpcJSON('copySetting', {
                                pageId: pageId,
                                setValue: setValue,
                                pages: selKey,
                                pageStyles: pageStyles,
                                header: header,
                                footer: footer,
                                headerStatic: headerStatic,
                                footerStatic: footerStatic
                            },
                            function () {
                                Tips('success', '复制成功', 2000)
                            });
                            fn()
                        })
                    }
                } else {
                    fn()
                }
            },
            onClose: function () {
                top.$('#copyContainerScroll').getNiceScroll().remove()
            },
            onConfirm: function () { }
        });
        $('input[role="style"]', el).each(function () {
            if (!$('#' + $(this).val(), pageBody).length) {
                $(this).attr('disabled', true)
            }
        });
        top.$('#copyContainerScroll').niceScroll({
            autohidemode: false,
            bouncescroll: true,
            cursorwidth: 5
        });
        rpcJSON('getPageTree', {},
        function (data) {
            tree = top.$('#copyTreeContainer').dynatree({
                checkbox: true,
                selectMode: 3,
                children: data,
                onExpand: function () {
                    top.$('#copyContainerScroll').getNiceScroll().resize()
                }
            }).dynatree("getTree");
            top.$('#copyContainerScroll').getNiceScroll().resize()
        })
    };
    if (saveBtn.hasClass('active')) {
        top.Confirm('本页还有改动未保存，需要保存后再继续',
        function () {
            save(fn)
        },
        '', {
            confirmText: '保存并继续'
        })
    } else {
        fn()
    }
};
function insertStaticStyle() {
    $('<div id="staticStyle" style="display:none;">' + '<div id="body_static"><div id="body_static_style"></div>' + '<div id="wrapper_static"><div id="wrapper_static_style"></div>' + '<div id="container_static"><div id="container_static_style"></div>' + '<div id="header_static"><div id="header_static_style"></div>' + '<div id="headerWrapper_static"><div id="headerWrapper_static_style"></div>' + '<div id="headerContainer_static"><div id="headerContainer_static_style"></div>' + '</div>' + '</div>' + '</div>' + '<div id="main_static"><div id="main_static_style"></div>' + '<div id="mainWrapper_static"><div id="mainWrapper_static_style"></div>' + '<div id="mainContainer_static"><div id="mainContainer_static_style"></div>' + '</div>' + '</div>' + '</div>' + '<div id="footer_static"><div id="footer_static_style"></div>' + '<div id="footerWrapper_static"><div id="footerWrapper_static_style"></div>' + '<div id="footerContainer_static"><div id="footerContainer_static_style"></div>' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>').prependTo(pageLayout)
};
toolsMain.delegate('a[role="copySetting"]', click, copySetting);
var pageBody,
pageLayout;
function makePage(frameObj, frameBody) {
    $HASH['iframeObj'] = frameObj;
    pageBody = frameBody;
    pageData = $HASH['iframeObj'].pageData;
    pageLayout = $('div.layout:first', frameBody);
    $HASH['siteSkinTempId'] = pageData.skinId;
    for (key in showTools) {
        if (showTools[key]) {
            pageBody.addClass(key)
        }
    };
    $('div.elementContainer,div[path="container"]', pageLayout).each(function () {
        if (!$(this).children('div[path],#app_frame,#user_frame').length) {
            $(this).append(getEmptyEl())
        }
    });
    if (!$('#staticStyle', pageLayout).length) {
        insertStaticStyle()
    };
    setElTools();
    selectedBody();
    frameObj.setIframeScrollTop();
    $('#pagePanel').animate({
        opacity: 1
    });
    $('#iframeLoading').fadeOut(function () {
        $('#iframeLoading').remove()
    })
};
$(window).resize(resizeIframe);